<?php
// 开启会话以记录敲木鱼的次数
session_start();

// 初始化敲木鱼次数，如果会话中不存在该值，则初始化为 0
if (!isset($_SESSION['knock_count'])) {
    $_SESSION['knock_count'] = 0;
}

// 处理敲木鱼的请求
if (isset($_POST['knock'])) {
    $_SESSION['knock_count']++;
}
?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>敲木鱼游戏</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            background-color: #f4f4f4;
        }

        h1 {
            color: #333;
        }

        #wooden-fish {
            width: 200px;
            height: 200px;
            margin: 20px auto;
            cursor: pointer;
        }

        #count {
            font-size: 24px;
            color: #555;
        }
    </style>
</head>

<body>
    <h1>敲木鱼游戏</h1>
    <img id="wooden-fish" src="https://cdn-icons-png.flaticon.com/512/5589/5589173.png" alt="木鱼" onclick="knockWoodenFish()">
    <p id="count">敲木鱼次数: <?php echo $_SESSION['knock_count']; ?></p>

    <!-- 音效元素 -->
    <audio id="knock-sound" src="https://www.soundjay.com/wood/wood-hit-1.wav" preload="auto"></audio>

    <script>
        function knockWoodenFish() {
            // 播放敲木鱼音效
            const audio = document.getElementById('knock-sound');
            audio.currentTime = 0;
            audio.play();

            // 发送 POST 请求更新敲木鱼次数
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'index.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 更新页面上的敲木鱼次数
                    const countElement = document.getElementById('count');
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(xhr.responseText, 'text/html');
                    const newCount = doc.getElementById('count').textContent;
                    countElement.textContent = newCount;
                }
            };
            xhr.send('knock=1');
        }
    </script>
</body>

</html>